package org.diffshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.diffshop.common.enums.BizCodeEnum;
import org.diffshop.common.exception.RRException;
import org.diffshop.common.to.SpuBoundTO;
import org.diffshop.common.utils.PageUtils;
import org.diffshop.common.utils.Query;
import org.diffshop.common.utils.R;
import org.diffshop.product.dao.PmsSpuInfoDao;
import org.diffshop.product.entity.PmsSpuInfoEntity;
import org.diffshop.product.entity.SpuInfoDescEntity;
import org.diffshop.product.feign.CouponFeignService;
import org.diffshop.product.service.*;
import org.diffshop.product.vo.BaseAttrs;
import org.diffshop.product.vo.Bounds;
import org.diffshop.product.vo.SpuSaveVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service("pmsSpuInfoService")
public class PmsSpuInfoServiceImpl extends ServiceImpl<PmsSpuInfoDao, PmsSpuInfoEntity> implements PmsSpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private PmsSkuInfoService skuInfoService;
    @Autowired
    private PmsSpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    /**
     * 查询分页带条件
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<PmsSpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 注：当不是根据catelogId、brandId查询时，它们的值都默认为0
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq(PmsSpuInfoEntity::getCatalogId, catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq(PmsSpuInfoEntity::getBrandId, brandId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq(PmsSpuInfoEntity::getPublishStatus, status);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq(PmsSpuInfoEntity::getId, key).or().like(PmsSpuInfoEntity::getSpuName, key);
            });
        }

        IPage<PmsSpuInfoEntity> page = this.page(
                new Query<PmsSpuInfoEntity>().getPage(params), queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品发布信息
     *
     * @param saveVO
     */
    @GlobalTransactional
    @Override
    public void saveDetail(SpuSaveVO saveVO) {
        // 1 保存商品信息 pms_spu_info
        PmsSpuInfoEntity spuInfoEntity = new PmsSpuInfoEntity();
        BeanUtils.copyProperties(saveVO, spuInfoEntity);
        baseMapper.insert(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        // 2 保存商品信息介绍 pms_spu_info_desc
        if (saveVO.getDecript() != null && saveVO.getDecript().size() > 0) {
            String decript = StringUtils.join(saveVO.getDecript(), ",");
            SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
            descEntity.setSpuId(spuId);
            descEntity.setDecript(decript);
            spuInfoDescService.save(descEntity);
        }

        // 3 保存商品图片 pms_spu_images
        List<String> images = saveVO.getImages();
        spuImagesService.saveSpuImageInfo(spuId, images);

        // 4 保存spu积分设置信息 sms_spu_bounds
        Bounds bounds = saveVO.getBounds();
        if (bounds != null && bounds.getBuyBounds().compareTo(BigDecimal.ZERO) == 1 && bounds.getGrowBounds().compareTo(BigDecimal.ZERO) == 1) {
            SpuBoundTO spuBoundTO = new SpuBoundTO();
            BeanUtils.copyProperties(bounds, spuBoundTO);
            spuBoundTO.setSpuId(spuId);
            R result = couponFeignService.saveSpuBoundInfo(spuBoundTO);
            if (result.getCode() != 0) {
                log.error("保存spu积分设置信息失败！" + result.getMsg());
                throw new RRException(BizCodeEnum.UNKNOWN_EXCEPTION.getMsg(), BizCodeEnum.UNKNOWN_EXCEPTION.getCode());
            }
        }

        // 5 保存商品属性信息 pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVO.getBaseAttrs();
        attrValueService.saveProductAttrBatch(spuId, baseAttrs);

        // 6 保存关于sku的信息 pms_sku_info pms_sku_sale_attr_value pms_sku_images sms_member_price
        skuInfoService.saveDetailBatch(spuId, saveVO.getCatalogId(), saveVO.getBrandId(), saveVO.getSkus());

        // TODO: 2024/6/23 目前只是两个微服务的事务，要是三个、四个...也能控制？
    }

}
